package ar.uba.fi.RSACryptoFiuba.model.keygeneration;

import ar.uba.fi.RSACryptoFiuba.model.InvalidValueException;
import ar.uba.fi.RSACryptoFiuba.model.RSACalculator;
import ar.uba.fi.RSACryptoFiuba.model.RSAMessage;
import ar.uba.fi.RSACryptoFiuba.model.RSAStep;

public class GenerateQStep extends RSAStep {
	
	@Override
	public void execute(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		Integer p = Integer.valueOf(keyGenerationMessage.getP());
		Integer q = RSACalculator.getRandomPrimeDifferentFrom(p);
		keyGenerationMessage.setQ(q.toString());
	}
	
	@Override
	public void undo(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		keyGenerationMessage.setQ("");
	}

	@Override
	public void test(RSAMessage message) {
		String element = message.getElementToEvaluate();
		verifyNumericalValue(element);
		Integer q = Integer.valueOf(element);
		boolean isValid = RSACalculator.isPrime(q);
		if(!isValid){
			throw new InvalidValueException("El número q debe ser primo.");
		}
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		if(keyGenerationMessage.getP().equals(element)){
			throw new InvalidValueException("El número q debe ser distinto de p.");
		}
		keyGenerationMessage.setQ(element);
	}

}
